package com.hmdp.listener;/*
@author name
@data 2025/1/18-21:50
*/



import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.UserHolder;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Component
@Slf4j
@RequiredArgsConstructor
public class VoucherStatusListener {

    @Autowired
    private IVoucherOrderService voucherOrderService;

    @Autowired
    private ISeckillVoucherService seckillVoucherService;

    @Autowired
    private RedisIdWorker redisIdWorker;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "voucher.pay.success.queue.test", durable = "true"),
            exchange = @Exchange(name = "voucher.topic"),
            key = "pay.success"
    ))
    @Transactional
    public void createVoucherOrder(@Payload Long voucherId,
                                   @Header("userId") Long userId) {
        UserDTO userDTO = new UserDTO();
        userDTO.setId(userId);
        UserHolder.saveUser(userDTO);
        log.info("优惠券下单完成，正在扣减用户为{}的优惠券，创建订单",userId);
        //一人一单
        int count = voucherOrderService.query()
                .eq("user_id", userId)
                .eq("voucher_id", voucherId).count();
        if(count > 0){
            //用户已经购买
            log.error("优惠券限购一张");
            return;
        }
//        扣减库存
        boolean success = seckillVoucherService.update()
                .setSql("stock= stock - 1")
                .eq("voucher_id", voucherId)
                .gt("stock",0)//where id = ？ and stock > 0
                .update();
        if (!success) {
            log.error("优惠券已经抢完");
            return;
        }
        //.创建订单
        VoucherOrder voucherOrder = new VoucherOrder();
        // 订单id
        long orderId = redisIdWorker.nextId("order");
        voucherOrder.setId(orderId);
        // 用户id
        voucherOrder.setUserId(userId);
        // 代金券id
        voucherOrder.setVoucherId(voucherId);
        voucherOrderService.save(voucherOrder);
        return;
    }
}